$(function() {
	var callbackurl = getQueryString('callbackurl');

    if (window.localStorage) {
        var username1 = $.trim( localStorage.getItem("username"));
        var password1 =  $.trim(localStorage.getItem("password"));
        if(username1!='' && password1 !=''){
            $(".login-username").val(username1);
            $(".login-password").val(password1);
            $('#checked').prop('checked',true)
        }
    } else {
        alert('This browser does NOT support localStorage');
    }
	var loginSubmit = function(paramObject) {
		$.ajax({
			type: 'POST',
			dataType: 'json',
			data: {
				username: paramObject.username,
				grant_type: 'password',
				client_id: 'facecompare',
				client_secret: '123456',
				password: paramObject.password
			},
			url: '/api/auth/v1/token',

			success: function(result) {
				console.log(result);
				if(result.code === 0 && callbackurl) {
					var joinstr = '?';
					if(callbackurl.indexOf('?') > -1) {
						joinstr = '&';
					}
					window.location = callbackurl + joinstr + 'code=' + result.data.access_token;
				}else{

					$('#text-msg').html(result.msg);
				}
			}
		});
	}

	$('.login-username-class, .login-password-class').on('focus', function() {

		if($(this).hasClass('login-username')) {

			$('.login-username-msg').text("");

		};
		if($(this).hasClass('login-password')) {
			$('.login-password-msg').text("");
		};


	})

	$(".login-submit-class").on('click', function() {
		var username = $(".login-username").val();
		var password = $(".login-password").val();


		var submitMsgUsername = "";
		var submitMsgPassword = "";
		if(!username) {
			submitMsgUsername = "用户名必须填写";
			$('.login-username-msg').text(submitMsgUsername);
			return;
		}
		if(!password) {
			submitMsgPassword = " 密码必须填写";
			$('.login-password-msg').text(submitMsgPassword);
			return;
		}

        if($('#checked').prop('checked')) {
            if (window.localStorage) {
                localStorage.setItem("username", username);
                localStorage.setItem("password", password);
            } else {
                alert('This browser does NOT support localStorage');
            }
        }else{
            if(window.localStorage){
                localStorage.removeItem("username");
                localStorage.removeItem("password");
            }else{
                alert('This browser does NOT support localStorage');
            }
        }
		loginSubmit({
			username: username,
			password: password
		});

	});

	function getQueryString(name) {
		var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
		var r = window.location.search.substr(1).match(reg);
		if(r != null) {
			return unescape(r[2]);
		}
		return null;
	}
})